package com.linghang.association.interceptor;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linghang.association.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
 * @author LinyaT052
 * @date 2022年07月18日 9:53
 * token拦截器类
 * 拦截登录请求，验证token
 */
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();
        //令牌建议放在请求头中，获取请求头中令牌
        String token = request.getHeader("token");
        String url = request.getRequestURI().toString();
        System.out.println("本次拦截Url为：http://localhost/"+url);
        try{
            JwtUtil.verify(token);//验证令牌
            return true;//放行请求
        }catch (SignatureVerificationException e){//捕获签名不一致异常
            e.printStackTrace();
            map.put("msg","无效签名");
        }catch (TokenExpiredException e){//捕获签名过期异常
            e.printStackTrace();
            map.put("msg","签名过期");
        }catch(AlgorithmMismatchException e){//捕获签名算法不一致异常
            map.put("msg","token算法不一致");

        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token失效");
        }
        map.put("state",false);//设置状态信息
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }
}
